package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import cn.tedu._03vehicle.mapper.UserMapper;
import cn.tedu._03vehicle.pojo.dto.UserLoginParam;
import cn.tedu._03vehicle.pojo.dto.UserRegParam;
import cn.tedu._03vehicle.pojo.entity.User;
import cn.tedu._03vehicle.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@Tag(name="用户管理模块")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("reg")
    @Operation(summary="添加用户")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody @Validated UserRegParam userRegParam){
        log.debug("userRegParam"+ userRegParam);
        //1接收客户端传递的数据已完成2.合法性校验暂时不做3校验用户名是否被占用[SELECT接口]
        //被占用
        String username=userRegParam.getUsername();
       int i=userMapper.selectByUsername(username);
       if (i>0){
           return new JsonResult(StatusCode.USERNAME_EXISTS);
       }
       //未被占用
        User user=new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insertUser(user);
        return  JsonResult.ok();//没有数据返回的

    }
    //登录功能
    @PostMapping("login")
    @ApiOperationSupport(order = 20)
    @Operation(summary = "用户登录")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("userLoginParam="+userLoginParam);
        UserVO userVO=userMapper.selectByUsernameAndPassword(userLoginParam);
        if(userVO != null){
            //将用户信息保存在session中 保存在服务端的内存中（没保存到数据库）
            session.setAttribute("user",userVO);
            return JsonResult.ok(userVO);
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }
    //获取当前用户功能
    @GetMapping ("currentUser")
    @Operation(summary = "获取当前用户")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session){
        UserVO userVO=(UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }
    //退出登录
    @GetMapping("logout")
    @Operation(summary = "退出登录功能")
    @ApiOperationSupport(order = 40)
    public void logout(HttpSession session){
        session.removeAttribute("user");

    }


}
